package com.ruoyi.web.controller.home;


import com.github.pagehelper.PageInfo;
import com.ruoyi.system.domain.Post;
import com.ruoyi.system.domain.Reply;
import com.ruoyi.system.service.PostService;
import com.ruoyi.system.service.ReplyService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/home/post")
public class PostController {

    @Resource
    private PostService postService;

    @Resource
    private ReplyService replyService;

    @GetMapping("/list")
    public Map<String, Object> postList(@RequestParam(defaultValue = "1") int pageNum,
                                        @RequestParam(defaultValue = "10") int pageSize) {
        Map<String, Object> result = new HashMap<>();
        PageInfo<Post> pageInfo = postService.getPostsByPage(pageNum, pageSize);
        result.put("code", 200);
        result.put("data", pageInfo.getList());
        result.put("total", pageInfo.getTotal());
        result.put("pages", pageInfo.getPages());
        return result;
    }

    @GetMapping("/{id}")
    public Map<String, Object> getPost(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        Post post = postService.getPostById(id);
        if (post != null) {
            result.put("code", 200);
            result.put("data", post);
            postService.updateClickCount(id); // 点击数+1
        } else {
            result.put("code", 404);
            result.put("msg", "帖子不存在");
        }
        return result;
    }

    @PostMapping("/reply")
    public Map<String, Object> reply(@RequestBody Reply reply) {
        reply.setReplyDate(new Date());
        Map<String, Object> result = new HashMap<>();
        if (replyService.insertReply(reply) > 0) {
            result.put("code", 200);
            result.put("msg", "发布成功");
        } else {
            result.put("code", 500);
            result.put("msg", "发布失败");
        }
        return result;
    }

    @PostMapping("/add")
    public Map<String, Object> addPost(@RequestBody Post post) {
        Map<String, Object> result = new HashMap<>();
        if (postService.addPost(post) > 0) {
            result.put("code", 200);
            result.put("msg", "发布成功");
        } else {
            result.put("code", 500);
            result.put("msg", "发布失败");
        }
        return result;
    }
}